package me.muci.B_netty.NIO;

import org.junit.Test;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * ClassName: MapperBufferTest
 * <p>
 * Description: 可以让文件在内存(堆外)中直接修改，操作系统不需要拷贝一次，
 * <p>
 * date: 2021/8/20 11:38
 *
 * @author muci
 * @since JDK 1.8
 */
public class MappedBufferTest {

    @Test
    public void testUpdateFile() throws IOException {
        RandomAccessFile randomAccessFile = new RandomAccessFile("src\\main\\resources\\NIO\\mappedBuffer\\read.txt", "rw");

        FileChannel channel = randomAccessFile.getChannel();

        /**
         * 参数一：读写模式
         * 参数二：起始位置
         * 参数三：映射到内存的大小，即将文件的多少个字节映射到内存
         */
        MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);
        mappedByteBuffer.put(0,(byte)'M');
        mappedByteBuffer.put(1,(byte)'U');
        mappedByteBuffer.put(2,(byte)'C');
        mappedByteBuffer.put(3,(byte)'I');

        randomAccessFile.close();
    }
}
